/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#pragma once

template <typename T>
class ISafeLocalFileImpl : public ISafeLocalFile
{
public:
    ISafeLocalFileImpl(void)
        : m_bSafeFile(false)
    {
        ATLTRACE( _T("ISafeLocalFileImpl::ISafeLocalFileImpl()\n") );
    }

    STDMETHOD(GetSafe)(VARIANT_BOOL* pvbSafe)
    {
        if (!pvbSafe)
            return E_POINTER;

        *pvbSafe = ToVariant(m_bSafeFile);

        return S_OK;
    }

    STDMETHOD(SetSafe)(VARIANT_BOOL vbSafe)
    {
        m_bSafeFile = (VARIANT_TRUE == vbSafe);

        return S_OK;
    }

    STDMETHOD(GetPath)(BSTR* pbsPath)
    {
        if (!pbsPath)
            return E_POINTER;

        *pbsPath = CComBSTR(m_strPath).Detach();

        return S_OK;
    }

    STDMETHOD(Init)(BSTR bsNativePath, VARIANT_BOOL vbSafe)
    {
        if (!bsNativePath || !*bsNativePath)
            return E_INVALIDARG;

        ATLTRACE( L"ISafeLocalFileImpl::Init(%s, %s)\n", bsNativePath, (VARIANT_TRUE == vbSafe) ? L"true" : L"false" );

        m_strPath = bsNativePath;
        m_bSafeFile = (VARIANT_TRUE == vbSafe);

        return S_OK;
    }

    bool IsSafePath(BSTR filePath)
    {
        wchar_t szPath[MAX_PATH+1];
        ZeroMemory(szPath, sizeof(szPath));
        RETURN_FAILED(::SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath))
        if (IsOSVistaOrHigher())
            wcscat_s(szPath, L"Low");
#ifndef _PROJECT_NAME
#error Please set _PROJECT_NAME to Project Name
#endif
        wcscat_s(szPath, L"\\");
        wcscat_s(szPath, _PROJECT_NAME);

        return (0 == wcsnicmp(szPath, m_strPath, wcslen(szPath)));
    }
protected:
    CStringW m_strPath;
    bool     m_bSafeFile;
};
